#!/user/bin/env python
# -*- coding: utf-8 -*-
"""
Author: Lhy
Description: 工具模块
"""
import json

from PyQt5 import QtCore
from .base import BaseModule
from typing import Dict, Any
import gui.controls.envs as envs
from ..pops import Pops

import gui.controls.globalvar as GL
import gui.controls.settings as ST
import gui.controls.apis as apis

import os
from ..uis import DlgImportRepairSchemeStrengthModel
from ..params_model import DlgThemeSwitch
from ..project import project_manager
from ..actions import Actions


class Tools(BaseModule):
    """工具类模块"""

    def __init__(self):
        super().__init__()

        current_file = os.path.abspath(__file__)
        # 从 plugins/DUT_tiankuo/ipimas/toolbar.py 向上获取到主程序根目录
        self.main_path = os.path.normpath(os.path.join(current_file, "../../../../.."))
        # 获取 desktop 路径
        path = self.main_path.replace("\\", "/")
        self.desktop_path = f"{path}/desktop"

    def init_category(self, ribbon: envs.Ribbonbar) -> Any:
        """初始化工具栏项
        Args:
            ribbon: 工具栏
        Returns:
            Any: 工具栏项
        """
        categoryTools = ribbon.add_category("工具")
        pannelThemeSwitching = ribbon.add_panel("工作流", categoryTools, titleHide=True)
        ribbon.add_large_btn(
            pannelThemeSwitching,
            {
                "title": "主题切换",
                "style": "large",
                "styleSheet": "margin-right:10px; padding: 10px 20px;",
                "action": lambda *args: self.theme_switching(),
            },
        )

        return categoryTools

    def init_dock(self, tree) -> None:
        data = [
            {
                "title": "工具",
                "children": [
                    {
                        "title": "主题切换",
                        "events": {"dbClick": lambda params: self.theme_switching()},
                    },
                ],
            }
        ]
        tree._set_data(data)

    def theme_switching(self):
        """导入模型"""
        py3d = envs.GL.get_value("py3d")
        dlg = DlgThemeSwitch.show(py3d)
        cfgIndex = {}
        with open("config/sys/index.json", "r", encoding="utf-8") as file:
            cfgIndex = json.load(file) or {}
        theme = {"theme": cfgIndex.get("theme")}
        if dlg:
            dlg.init(theme)
            dlg.themeSwitch_save_signal.connect(
                lambda data: self.themeSwitch_save_signal(data)
            )

    def themeSwitch_save_signal(self, data: dict = {}):
        configData = {}
        with open("config/sys/index.json", "r", encoding="utf-8") as file:
            configData = json.load(file) or {}
            configData["theme"] = data.get("theme", "dark")

        with open("config/sys/index.json", "w", encoding="utf-8") as file:
            json.dump(configData, file, indent=2, ensure_ascii=False)

        py3d = envs.GL.get_value("py3d")
        self._reset_theme(py3d)
        self.set_theme(py3d)

    def _reset_theme(self, widget):
        """重置所有样式设置"""
        from PyQt5.QtWidgets import QApplication

        app = QApplication.instance()

        # 重置样式表
        widget.setStyleSheet("")
        app.setStyleSheet("")
        # 重置QStyle
        app.setStyle("")  # 重置为默认样式
        # 如果是ModernWindow需要特殊处理
        if hasattr(self, "_modern_window"):
            self._modern_window.close()
            del self._modern_window

    def set_theme(self, py3d):
        """读取已经初始化好的配置文件，设置主界面配置信息"""

        cfgIndex = {}
        with open("config/sys/index.json", "r", encoding="utf-8") as file:
            cfgIndex = json.load(file) or {}

        theme = cfgIndex.get("theme", "dark")  # dark or light
        themeOptions = cfgIndex.get("themeOptions", {})

        # 设置主程序主题
        useThemeSystem = themeOptions.get(
            "useThemeSystem", ""
        )  # "" or qdarkstyle or qdarktheme
        if theme == "dark":
            import qdarkstyle
            from qdarkstyle.light.palette import LightPalette
            from qdarkstyle.dark.palette import DarkPalette

            # 加载基础样式表
            base_stylesheet = qdarkstyle.load_stylesheet(
                qt_api="pyqt5",
                palette=theme == "dark" and DarkPalette or LightPalette,
            )
            # 添加自定义按钮样式
            custom_styles = """
            /* 修复 QPushButton 间距问题 */
            QPushButton {
                padding: 6px;
                min-width: 64px;
            }
            
            """

            # 合并样式表
            py3d.setStyleSheet(base_stylesheet + custom_styles)

            ribbonbar = GL.get_value("ribbonbar")
            ribbonbar.setStyleSheet(open("styles/base.qss", "r").read())

        elif theme == "light":

            from PyQt5.QtWidgets import QApplication
            import qtmodern.styles

            app = QApplication.instance()
            qtmodern.styles.light(app)  # 正确 - 内部会处理好样式设置
            # 应用自定义样式
            app.setStyleSheet(open("styles/qtmodern_light.qss", "r").read())

            ribbonbar = GL.get_value("ribbonbar")
            ribbonbar.setStyleSheet(open("styles/base_light.qss", "r").read())

        elif useThemeSystem == "qdarktheme":
            import qdarktheme

            qdarktheme.setup_theme(theme)
            # 覆盖背景为蓝色，字体为白色
            py3d.setStyleSheet(
                """
                QWidget {
                    color: #1E90FF;  /* 蓝色背景 */
                    background-color: white;               /* 白色字体 */
                }
            """
            )
            useThemeSystem = "qdarktheme"
            customColors = themeOptions.get("customColors", {})
            themeCustomColors = customColors.get(theme, {})
            if themeCustomColors:
                qdarktheme.setup_theme(custom_colors=themeCustomColors)

        # 设置是否隐藏view 的tabbar
        apis.hide_view_tab(cfgIndex.get("hideTabBar", False))
        # 设置视图的背景色
        self.init_config()

    def init_config(self):
        # 初始化 默认背景色
        self.timer = QtCore.QTimer()
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.init_once)
        self.timer.start(10)

    def init_once(self, *args, **kwargs):
        # 设置视图的背景色
        # cfgIndex = ST.get_index_data() or {}
        cfgIndex = {}
        with open("config/sys/index.json", "r", encoding="utf-8") as file:
            cfgIndex = json.load(file) or {}
        theme = cfgIndex.get("theme", "light")
        viewBackgroundColor = cfgIndex.get("viewBackgroundColor").get(
            theme, [[93, 212, 255], [255, 253, 218]]
        )
        apis.set_view_bgcolor(viewBackgroundColor)
        GL.set_value("showGridModel", cfgIndex.get("showGridModel", True))
